package client

import (
	"log"
	"sync"

	"iclient/file"
	"iclient/tcp"
)

// FileClient ifile客户端
type FileClient struct {
	Pool *tcp.Pool
}

// MakeFileClient 创建客户端
func MakeFileClient(remoteAddr string, maxConn int, maxConnTime int) *FileClient {
	pool := tcp.MakePool(remoteAddr, maxConn, maxConnTime)
	return &FileClient{
		Pool: pool,
	}
}

// SendFiles 发送文件
func (fc *FileClient) SendFiles(parentPath string) {
	metaChan := make(chan *file.Meta)

	go func() {
		file.GetFilesAllToChan(parentPath, metaChan)
		close(metaChan)
	}()

	var wg sync.WaitGroup

	for {
		fileHandler := file.MakeFileHandler(metaChan)

		resource, err := fileHandler.GetResource()
		if err != nil {
			break
		}

		wg.Add(1)
		go func() {
			defer wg.Done()
			tcp.Transfer(fc.Pool, fileHandler, resource)
		}()
	}

	wg.Wait()
	log.Println("所有文件均已发送完成")
}
